from datetime import datetime
import os
import random
from functools import wraps 
import time

def retry(retries: int = 3, delay: float = 1):
    """
    函数执行失败时，重试

    :param retries: 最大重试的次数
    :param delay: 每次重试的间隔时间，单位 秒
    :return:
    """

    # 校验重试的参数，参数值不正确时使用默认参数
    if retries < 1 or delay <= 0:
        retries = 3
        delay = 1

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # 第一次正常执行不算重试次数，所以retries+1
            for i in range(retries + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    # 检查重试次数
                    if i == retries:
                        print(f"Error: {repr(e)}")
                        print(f'"{func.__doc__}()" 调用失败，已重试{retries}次')
                        break
                    else:
                        print(
                            f"Error: {repr(e)}，{delay}秒后第[{i+1}/{retries}]次重试..."
                        )
                        time.sleep(delay)

        return wrapper

    return decorator

@retry(retries=2, delay=0.1)
def pay():
    '''支付接口'''
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print(f"[{now}]: 开始调用支付接口")
    rd = random.randint(1,10)
    if rd in (2,4,6):
        print('调用支付接口成功！返回值：%d'%rd)
        return rd
    else:
        raise Exception("调用支付接口超时...")
        return None

if __name__ == "__main__":
    r = pay()  # 重试2次，每次间隔2秒
    
print(datetime.now().strftime('%Y-%m-%d-%H'))